namespace Leey.Net.eTerm
{
    using System;
    using System.Collections;
    using System.IO;
    using System.Net.Sockets;
    using System.Text;
    using System.Threading;
    using System.Windows.Forms;
    using System.Xml;

    internal class program
    {
        private byte[] CurCmdByte = null;
        private EtermConnection ec;
        private int iInterval = 150;
        private int iTimeout = 0x1f40;
        private Hashtable m_hash;
        private Hashtable m_hashSocket;
        private object oCmdCB;
        private object oIncept;
        private DateTime SendTime;
        private MyTcpIpServer server;

        private void CmdCB(object sender, CmdResult result)
        {
            object obj2 = new object();
            try
            {
                lock (obj2)
                {
                    int milliseconds = 0;
                    try
                    {
                        TimeSpan span = (TimeSpan) (DateTime.Now - this.SendTime);
                        milliseconds = span.Milliseconds;
                    }
                    catch
                    {
                    }
                    Log.Write(string.Concat(new object[] { "**************************************", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:ffff"), "收到航信返回数据.用时:", milliseconds, "毫秒." }));
                    Log.Write(result.Data);
                    this.Print(DateTime.Now.ToString() + "收到航信返回的数据：\r\n" + result.Data);
                    EtermConnection ecChannel = result.CmdPacket.EcChannel;
                    string key = result.CmdPacket.EcChannel.UserName.Substring(0, 8);
                    Log.Write("***收到数据的用户名：" + key);
                    string data = result.Data;
                    if ((data == null) || (data.Trim() == ""))
                    {
                        this.SentCms(this.ec, this.CurCmdByte);
                    }
                    if (this.m_hashSocket.ContainsKey(key))
                    {
                        Socket socket = (Socket) this.m_hashSocket[key];
                        if (socket != null)
                        {
                            try
                            {
                                byte[] bytes = Encoding.Default.GetBytes(data);
                                socket.Send(result.OrignalData);
                                Log.Write("返回给客户端完毕：");
                                this.Print(DateTime.Now.ToString() + "返回给客户端完毕");
                            }
                            catch (Exception exception)
                            {
                                this.m_hashSocket.Remove(key);
                                Log.Write("CmdCB is err=：" + exception.Message);
                                this.Print("CmdCB is Error" + exception.Message);
                            }
                        }
                        else
                        {
                            Log.Write("Socket 出错！");
                            this.Print("Socket 出错！");
                        }
                    }
                    else
                    {
                        Log.Write("***No Socket!!!");
                    }
                }
            }
            catch (Exception exception2)
            {
                Log.Write("+++CmdCb error" + exception2.Message);
                this.Print("+++CmdCb error  Socket 出错！");
            }
        }

        public void Init443()
        {
            try
            {
                this.oIncept = new object();
                this.oCmdCB = new object();
                this.server = new MyTcpIpServer();
                NewPara para = new NewPara();
                para.OpenXml(Application.StartupPath + @"\Eterm.xml");
                string s = para.FindTextByPath("//eg/Port");
                this.server.TcpIpServerPort = int.Parse(s);
                this.server.InceptServer += new InceptServerEvent(this.server_Incept);
                this.server.ErrorServer += new ErrorServerEvent(this.server_Error);
                this.server.Listening();
                this.Print("Lissing at:" + s);
                this.m_hashSocket = new Hashtable();
            }
            catch (Exception exception)
            {
                this.Print("Error" + exception.Message);
            }
        }

        public bool LoadConfig()
        {
            string innerText;
            bool flag = false;
            //string str = "http://b2bws.cn95161.com/egws.asmx";
            NewPara para = new NewPara();
            if (File.Exists(Application.StartupPath + @"\Eterm.xml"))
            {
                if (!para.OpenXml(Application.StartupPath + @"\Eterm.xml"))
                {
                    MessageBox.Show("XML打开出错！");
                    return false;
                }
                innerText = para.FindNodeByPath("//eg//KEY").InnerText;
                try
                {
                    int num = int.Parse(para.FindTextByPath("//eg/Timeout"));
                    this.iTimeout = num;
                    this.iInterval = int.Parse(para.FindTextByPath("//eg/ExeInterval"));
                }
                catch
                {
                }
                switch (innerText)
                {
                    case "":
                    case null:
                        return false;
                }
            }
            else
            {
                MessageBox.Show("没找到XML！");
                return false;
            }
            //egws egws = new egws(str);
            //NewPara para2 = new NewPara();
            //para2.AddPara("cm", "Check443");
            //para2.AddPara("Key", innerText);
            //string xML = para2.GetXML();
            //NewPara para3 = new NewPara(egws.getEgSoap(xML));
            //if (para3.FindNodeByPath("//eg//Flag").InnerText != "true")
            //{
            //    MessageBox.Show("请取得授权后再使用软件！");
            //    return false;
            //}
            NewPara para4 = new NewPara();
            try
            {
                if (!File.Exists(Application.StartupPath + @"\Eterm.xml"))
                {
                    return flag;
                }
                if (para4.OpenXml(Application.StartupPath + @"\Eterm.xml"))
                {
                    XmlNode node = para4.FindNodeByPath("//eg/IPS");
                    for (int i = 0; i < node.ChildNodes.Count; i++)
                    {
                        XmlNode node3 = node.ChildNodes[i];
                        string str5 = node3.ChildNodes[0].ChildNodes[0].Value.ToString().Trim();
                        string str6 = node3.ChildNodes[1].ChildNodes[0].Value.ToString().Trim();
                        string str7 = node3.ChildNodes[3].ChildNodes[0].Value.ToString().Trim();
                        string str8 = node3.ChildNodes[4].ChildNodes[0].Value.ToString().Trim();
                        string str9 = node3.ChildNodes[5].ChildNodes[0].Value.ToString().Trim();
                        string str10 = node3.ChildNodes[6].ChildNodes[0].Value.ToString().Trim();
                        this.ec = new EtermConnection();
                        this.ec.Server = str7;
                        this.ec.Port = Convert.ToInt16(str8);
                        this.ec.UserName = str5;
                        this.ec.PassWord = str6;
                        if (str9 == "True")
                        {
                            this.ec.Ssl = true;
                        }
                        else
                        {
                            this.ec.Ssl = false;
                        }
                        this.ec.eTerminalType = (EtermConnection.TerminalType) Enum.Parse(typeof(EtermConnection.TerminalType), str10);
                        this.ec.AutoReConnect = true;
                        this.ec.AutoSI = true;
                        this.ec.KeepAlived = true;
                        this.ec.KeepReconnect = true;
                        this.ec.OnEtermConnectionStateChanged += new EtermConnection.EtermConnectionStateHandler(this.OnEcStateChanged);
                        this.ec.Open();
                        this.ec.SendNoResponseInterval = this.iTimeout;
                        this.ec.ExeInterval = this.iInterval;
                        this.Print(string.Concat(new object[] { "接收时限：", this.iTimeout.ToString(), "发送时限:", this.ec.ExeInterval }));
                        Thread.Sleep(500);
                    }
                    flag = true;
                    this.server.Listening();
                }
                else
                {
                    flag = false;
                }
            }
            catch (Exception)
            {
                flag = false;
            }
            return flag;
        }

        private static void Main(string[] args)
        {
            program program = null;
            try
            {
                program = new program();
                program.LoadConfig();
                program.Init443();
                Console.ReadLine();
            }
            catch (Exception exception)
            {
                program.Print(exception.Message);
                Console.ReadLine();
            }
        }

        private void OnEcStateChanged(object sender, StateClass.ConnectionState state)
        {
            this.Print(this.ec.UserName + ":" + state.ToString());
            Log.Write("**************************************" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:ffff") + "***" + this.ec.UserName + ":" + state.ToString());
        }

        public void Print(string message)
        {
            Console.WriteLine(message);
        }

        public void SentCms(EtermConnection ec, byte[] commandpacket)
        {
            try
            {
                CmdPacket packet = null;
                if (!ec.Is3In1)
                {
                    packet = new CmdPacket(commandpacket, new EtermConnection.CmdResultCB(this.CmdCB));
                    this.Print("构造普通指令包成功");
                    Log.Write("构造普通指令包成功");
                }
                else
                {
                    packet = new CmdPacket(commandpacket, true, new EtermConnection.CmdResultCB(this.CmdCB));
                    this.Print("构造三合一指令包成功");
                    Log.Write("构造普通指令包成功");
                }
                packet.EcChannel = ec;
                this.CurCmdByte = new byte[packet.CmdBytesLength];
                packet.EncodeCmdBytes.CopyTo(this.CurCmdByte, 0);
                this.SendTime = DateTime.Now;
                Log.Write("**************************************" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:ffff") + "发送给航信.");
                packet.Send();
            }
            catch (Exception exception)
            {
                Log.Write(string.Concat(new object[] { "++SentCms is err=", exception.Message, exception.StackTrace, exception.TargetSite }));
                this.Print("++SentCms is err=");
                if ((ec.m_ConnectionState != StateClass.ConnectionState.Logined) && (ec.m_ConnectionState == StateClass.ConnectionState.DisConnected))
                {
                    ec.Open();
                    Thread.Sleep(500);
                }
            }
        }

        private void server_Error(object sender, ErrorServerEventArgs e)
        {
            this.Print("连接 配置服务器SocketError " + e.Error);
        }

        private void server_Incept(object sender, InceptServerEventArgs e)
        {
            lock (this.oIncept)
            {
                Log.Write("收到客户端来的数据：");
                this.Print(DateTime.Now.ToString() + "Receive Client Data");
                try
                {
                    byte[] sourceArray = ((MemoryStream) e.Astream).GetBuffer();
                    if (sourceArray.Length < 0x25)
                    {
                        Log.Write("*************收到非法数据!\r\n");
                        this.Print("*************收到非法数据!");
                    }
                    else
                    {
                        byte[] destinationArray = new byte[0x10];
                        byte[] dst = new byte[sourceArray.Length - 0x10];
                        Array.Copy(sourceArray, destinationArray, 0x10);
                        System.Buffer.BlockCopy(sourceArray, 0x10, dst, 0, sourceArray.Length - 0x10);
                        string key = Encoding.Default.GetString(destinationArray).Substring(0, 9);
                        char ch = key[key.Length - 1];
                        key = key.Substring(0, 8);
                        if (key != string.Empty)
                        {
                            Log.Write("开始执行指令：");
                            this.Print(key + DateTime.Now.ToString() + ":开始执行指令");
                            if (ch == '$')
                            {
                                this.ec.Is3In1 = true;
                            }
                            else
                            {
                                this.ec.Is3In1 = false;
                            }
                            if (ch == '#')
                            {
                            }
                            Log.Write("***发送时用户名" + key);
                            if (!this.m_hashSocket.ContainsKey(key))
                            {
                                this.m_hashSocket.Add(key, e.ServerSocket);
                            }
                            Log.Write("准备发送给航信：");
                            this.Print(key + DateTime.Now.ToString() + ":准备发送给航信：");
                            this.SentCms(this.ec, dst);
                        }
                    }
                }
                catch (Exception exception)
                {
                    Log.Write("server_InceptServer：" + exception.Message);
                    this.Print("server_InceptServer：" + exception.Message);
                }
            }
        }
    }
}
